#include "getcontent.h"

GetContent::GetContent()
{
}

QString GetContent::getHomePath()
{
    QProcess *execCmd = new QProcess();
    QStringList params;
    QStringList getUserName;
    QStringList curHome;
    QString curUser = "";
    QString ret ="";
    QString tmpLine ="";
    QStringList contentList;
    QStringList tmpLineList;
    QString firstLine = "";
    QString curUsrPawdInfo = "";
    
    /* 使用who命令获取当前用户名，如果多用户登灵会产生问题*/
   /* execCmd->start("who", params);
    execCmd->waitForFinished();
    curUser = execCmd->readAllStandardOutput();
    getUserName = curUser.split(" ");
    curUser = getUserName[0];*/
    
    /*使用last命令获取首行still logged in的用户*/
    execCmd->start("last", params);
    execCmd->waitForFinished();
    ret = execCmd->readAllStandardOutput();
    
    //将整体返回的字符串按\n为一行，存储到list中
    for (auto ch:ret) {
    	if ('\n'!= ch) {
		tmpLine.append(ch);
    	}
    	else {
    		contentList.append(tmpLine);
    		tmpLine.clear();
    	}
    }
    
    //取第一个非root的用户
    int i= 0;
    do {
    	if (contentList[i].contains("root", Qt::CaseInsensitive)) {
    		continue;
    	}
    	else {
    		getUserName = contentList[i].split(" ");
    		curUser = getUserName[0];
    		break;
    	}
    	i++;
    } while (i<contentList.size());
    
    
    
    execCmd->start("bash", QStringList() << "-c" << "cat /etc/passwd | grep " + curUser);
    execCmd->waitForFinished();
    curUsrPawdInfo = execCmd->readAllStandardOutput();
    execCmd->close();
    
    curHome = curUsrPawdInfo.split(':');
    
    return curHome[5];
}

bool GetContent::checkLogPathExists(QString &logPath)
{
    QFile file(logPath);
    if (file.exists()) {
//        qDebug() << logPath << " Exists.";
        return true;
    }
    else {
//        qDebug() << logPath <<  " Not Exists.";
//        QMessageBox::critical(NULL, "提示", "文件不存在");
        return false;
    }
}

bool GetContent::checkLogPathEmpty(QString &logPath)
{
    QFile file(logPath);
    if (file.size()) {
        return false;
    }
    else {
//        qDebug() << logPath <<  " is Empty";
//        QMessageBox::critical(NULL, "提示", "该文件是一个空文件");
        return true;
    }
}

bool GetContent::checkDirPathExists(QString &dirPath)
{
    QDir dir(dirPath);
    if (dir.exists()) {
        qDebug() << dirPath << " Exists.";
        return true;
    }
    else {
        qDebug() << dirPath << "Not Exists.";
        QMessageBox::critical(NULL, "提示", "目录不存在");
        return false;
    }
}

int GetContent::getSubStringCount(QString &str)
{
    QString substr = "\x1b";
    QRegExp rx(substr);
    int count = 0;
    int pos = 0;
    while ((pos = rx.indexIn(str, pos)) != -1) {
    	++count;
    	pos += rx.matchedLength();
    }
    return count;
}

void GetContent::removeColorString(QString &str)
{
    int colorStringLeft = 0;
    int colorStringRight = 0;
    int pos = 0;
    int count = 0;
    int substrCount = getSubStringCount(str);
    QString substr = "\x1b";

    colorStringLeft = str.indexOf(substr, pos);
    
    for (int i=0; i<substrCount; i++) {
        colorStringRight = str.indexOf('m', colorStringLeft);
        if (colorStringRight != -1) {
            count = colorStringRight - colorStringLeft + 1;
            str.replace(colorStringLeft, count, "");
        }
        colorStringLeft = str.indexOf(substr, pos);
    }
}

QStringList GetContent::findMatchingFiles(QString &matchStr, QString path="/var/log/")
{
    QStringList fileList;
    QDir dir(path);
    QRegExp rxSource;
    rxSource.setPattern(matchStr);

    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Dirs);
    foreach (auto fileInfo, fileInfoList) {
        if (fileInfo.isFile()) {
            if (rxSource.indexIn(fileInfo.absoluteFilePath()) != -1) {
                fileList.append(fileInfo.absoluteFilePath());
            }
        }
    }
//    qDebug() << __FUNCTION__ << __LINE__ << "fileList:" << fileList;
    return fileList;
}

void GetContent::reverseQStringList(QStringList &str)
{
    QStringList temp;
    for (QStringList::reverse_iterator it=str.rbegin(); it!=str.rend(); it++) {
        temp.append(*it);
    }
    str = temp;
}

void GetContent::getWtmpContent(QStringList &logAll)
{
    QString logFile = "/var/log/wtmp";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    FILE *file = NULL;
    size_t len = 0;
    char *line = NULL;
    file = popen("last -xFf /var/log/wtmp | grep -v wtmp | grep -v runlevel | grep -v ^$", "r");
    if (!file) {
        qDebug() << "Open file error";
        return;
    }

    int i = 0;
    while (getline(&line, &len, file) != -1) {
        if (i++ >= limitCountItems) {
            break;
        }

        if (line[strlen(line) - 1] == '\n') {
            line[strlen(line) - 1] = '\0';
        }
        logAll.append(line);
    }
    pclose(file);
}

void GetContent::getSyslogContent(QStringList &logAll)
{
    QString logFile = "/var/log/syslog";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }
    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getBootlogContent(QStringList &logAll)
{
    QStringList files;
    QString matchStr = "boot\\.log";
    QString line = "";
    int limitCountItems = 10000;

    files = findMatchingFiles(matchStr);

    for (QStringList::Iterator logFile=files.begin(); logFile!=files.end(); logFile++) {
        QFile file(*logFile);
        if (!file.open(QIODevice::ReadOnly)) {
            qDebug() << "Open " << *logFile << " error";
            return;
        }

        QTextStream in(&file);
        int i = 0;
        while (!in.atEnd()) {
            if (i++ >= limitCountItems) {
                break;
            }

            line = in.readLine();
            if (line == "")
                continue;

            //去除结尾的'\r'
            line = line.replace('\r', ' ');
            //去除修饰颜色的字符串
            this->removeColorString(line);
            //qDebug() << line;
            logAll.append(line);
        }
//        qDebug() << logAll;
        file.close();
    }
}

void GetContent::getDpkglogContent(QStringList &logAll)
{
    QString logFile = "/var/log/dpkg.log";
    QString line = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
    reverseQStringList(logAll);
//    qDebug() << logAll;
    file.close();
}

void GetContent::getKernelContent(QStringList &logAll)
{
    QString logFile = "/var/log/kern.log";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getSoftwareUpdateContent(QStringList &logAll)
{
    QString logFile = "/var/log/alternatives.log";
    QString line = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
    reverseQStringList(logAll);
//    qDebug() << logAll;
    file.close();
}

void GetContent::getPrintContent(QStringList &logAll)
{
    QString logFile = "/var/log/cups/access_log";
    QString line = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
    reverseQStringList(logAll);
//    qDebug() << logAll;
    file.close();
}

void GetContent::getBurnContent(QStringList &logAll)
{
    QString logFile = "/var/log/brasero.log";
    QString line = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
//    qDebug() << logAll;
    file.close();
}

void GetContent::getAuditContent(QStringList &logAll)
{
    QString logFile = "/var/log/audit/audit.log";
    QString line = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
//    qDebug() << logAll;
    file.close();
}

void GetContent::getSessionContent(QStringList &logAll)
{
    QString logFile = "";
    QString line = "";
    int limitCountItems = 10000;

    logFile = getHomePath() + "/.xsession-errors";
//    qDebug() << logFile;
    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
//    qDebug() << logAll;
    file.close();
}

void GetContent::getXorgContent(QStringList &logAll)
{
    QString logFile = "/var/log/Xorg.0.log";
    QString line = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    QTextStream in(&file);
    int i = 0;
    while (!in.atEnd()) {
        if (i++ >= limitCountItems) {
            break;
        }

        line = in.readLine();
        if (line == "")
            continue;

        logAll.append(line);
    }
//    qDebug() << logAll;
    file.close();
}

void GetContent::getApplicationContent(QStringList &logAll)
{
    QString logFile = "/var/log/messages";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getDebugContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_debug";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getInfoContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_info";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getNoticeContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_notice";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getWarningContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_warning";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getErrorContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_err";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getCriticalContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_crit";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getAlertContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_alert";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}

void GetContent::getEmergContent(QStringList &logAll)
{
    QString logFile = "/var/log/level_emerg";
    QString line = "";
    QString lineFirst = "";
    int limitCountItems = 10000;

    if (!(fileExist = checkLogPathExists(logFile))) {
        return;
    }

    if ((fileEmpty = checkLogPathEmpty(logFile))) {
        return;
    }

    QFile file(logFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Open " << logFile << " error";
        return;
    }

    lineFirst = file.readLine();

    qint64 len = file.size() - 2;
    QByteArray c;
    int i = 0;
    while (len >= 0) {
        file.seek(len);
        c = file.read(1);
        if (c == "\n") {
            line = file.readLine();
            logAll.append(line);
            if (i++ >= limitCountItems) {
                break;
            }
        }
        len--;
    }
    logAll.append(lineFirst);
    file.close();
}



